using UnityEngine;
using System.Collections;

public class AnimatedButton : MonoBehaviour {

    
    public float timer = 0.15f;

    public int _nbAnim = 0;
    public bool _loop = false;
    private float time = 0;
    private int index = 0;
    private Vector2 sizeTexture;
	
	// Update is called once per frame
	void Update () {

        if (_nbAnim == 0)
            return;

        time += Time.deltaTime;

        if (time > timer)
        {
            index++;
            //Loop
            if (index >= _nbAnim && _loop)
            {
                index = 0;
            }
            //End Anim
            else if (index >= _nbAnim)
            {
                _nbAnim = 0;

                if(this.GetComponent<HUDButton>())
                    this.GetComponent<HUDButton>().AnimEnd();                
            }

            ComputeOffset();

            time = 0;
        }
	}

    void ComputeOffset()
    {

        if (_nbAnim == 0)
            return;
        this.renderer.material.mainTextureOffset = new Vector2((float)(index * (float)sizeTexture.x / (float)_nbAnim) / sizeTexture.x, 1);
    }

    void ComputeTilling()
    {
        if (_nbAnim == 0)
            return;
        this.renderer.material.mainTextureScale = new Vector2((float)1 / (_nbAnim), 1);
    }


    public void Play(int nbAnim, bool loop)
    {
        
        time = 0;
        index = 0;
        _loop = loop;
        _nbAnim = nbAnim;
        Texture texture = this.renderer.material.mainTexture;
        sizeTexture = new Vector2(texture.width, texture.height);

        ComputeTilling();
        ComputeOffset();
    }

}
